import React, {useRef, useState} from 'react';
import {Button, message, Modal, Tag} from 'antd';
import type {ProColumns} from '@ant-design/pro-table';
import ProTable, {ActionType} from '@ant-design/pro-table';
import {addAuth, authInfo, delAuth, getAuthList, updateAuth} from "@/pages/AuthConfig/service";
import {TableListItem} from "@/pages/AuthConfig/data";
import {PageContainer} from "@ant-design/pro-layout";
import AuthConfigForm from "@/pages/AuthConfig/components/AuthConfigForm";

const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在更新');
  const res = await updateAuth(fields);
  hide();
  if (res.code == 10000) {
    message.success('更新成功');
    return true;
  }
  message.error('更新失败，请重试');
  return false
};


const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  const res = await addAuth(fields);
  hide();
  if (res.code == 10000) {
    message.success('添加成功');
    return true;
  }
  message.error('更新失败，请重试');
  return false;
};

const handleRemove = async (id: number) => {
  const hide = message.loading('正在删除');

  const res = await delAuth({id: id});
  hide();
  if (res.code == 10000) {
    message.success('删除成功，即将刷新');
    return true;
  }
  message.error('删除失败，请重试');
  return false;

};

const authTypeEnum = {
  contents: {text: '目录', color: 'blue'},
  menu: {text: '菜单', color: 'cyan'},
  auth: {text: '权限', color: 'green'},
}

const AuthConfig: React.FC<any> = (props) => {

  const actionRef = useRef<ActionType>();

  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const [formTitle, setFormTitle] = useState<string>();
  const [stepFormValues, setStepFormValues] = useState<TableListItem>({});
  const [authList, setAuthList] = useState<TableListItem[]>();

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '权限类型',
      dataIndex: 'authType',
      render: (text, _) => text ?
        <Tag color={authTypeEnum[text as string].color}>{authTypeEnum[text as string].text}</Tag> : '-'
    },
    {
      title: '排序',
      dataIndex: 'sort',
      valueType: 'digit'
    },
    {
      title: '上级权限',
      dataIndex: 'pid',
      hideInTable: true,
    },
    {
      title: '唯一标示',
      dataIndex: 'guid',
      valueType: 'text',
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '图标名称',
      dataIndex: 'icon',
      valueType: 'text',
    },
    {
      title: '路由地址',
      dataIndex: 'routePath',
      valueType: 'text',
    },
    {
      title: '组件名称',
      dataIndex: 'componentName',
      valueType: 'text',
    },
    {
      title: '权限所属',
      dataIndex: 'type',
      valueType: 'select',
      valueEnum: {
        Backend: {text: 'Backend - 后台系统'},
        SysAdmin: {text: 'SysAdmin - 配置系统'},
        Customer: {text: 'Customer - 会员后台'},
        Api: {text: 'Api - API'},
        App: {text: 'App - APP'}
      },
    },
    {
      title: 'url',
      dataIndex: 'url',
      valueType: 'text',
    },
    {
      title: '请求方式',
      dataIndex: 'mode',
      valueEnum: {
        GET: {text: 'GET'},
        POST: {text: 'POST'},
        PUT: {text: 'PUT'},
        DELETE: {text: 'DELETE'}
      },
      valueType: 'select',
    },
    {
      title: '是否显示',
      dataIndex: 'display',
      valueEnum: {
        no: {text: '否', status: 'Default'},
        yes: {text: '是', status: 'Success'},
      },
    },
    {
      title: '权限控制',
      dataIndex: 'auth',
      valueEnum: {
        no: {text: '否', status: 'Default'},
        yes: {text: '是', status: 'Success'},
      },
    },
    {
      title: '操作',
      width: 180,
      key: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a key="link" onClick={() => {
          authInfo({id: record.id}).then(res => {
            if (res.code === 10000) {
              setStepFormValues(res.data);
              setFormTitle("修改权限");
              handleModalVisible(true);
            }
          })
        }}>修改</a>,
        <a key="link2" onClick={() => record.id && removeItem(record.id)}>删除</a>,
      ],
    },
  ];

  const removeItem = (id: number) => {
    Modal.confirm({
      title: '确认',
      content: '是否确认删除本权限及以下所有权限？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        let promise = await handleRemove(id);
        if (promise && actionRef.current) actionRef.current.reload()
      },
    });
  };

  return (
    <PageContainer>
      <ProTable<TableListItem>
        actionRef={actionRef}
        columns={columns}
        request={(params) => getAuthList().then(res => {
          const result = {data: [], success: false};

          if (res.code === 10000) {
            result.success = true;
            result.data = res.data || [];
            setAuthList([{name: '主目录', id: 0, children: result.data}])
          }
          return result;
        })}
        rowKey="id"
        search={false}
        dateFormatter="string"
        headerTitle="菜单管理"
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={() => {
            setFormTitle("添加权限");
            handleModalVisible(true);
          }}>
            添加权限
          </Button>,
        ]}
        pagination={false}
      />
      {modalVisible &&
      <AuthConfigForm
        title={formTitle}
        modalVisible={modalVisible}
        treeData={authList}
        initValue={stepFormValues}
        onCancel={() => {
          setStepFormValues({});
          handleModalVisible(false);
        }}
        onSubmit={async (value: any) => {
          let res;
          if (stepFormValues.id) {
            value.id = stepFormValues.id;
            res = handleUpdate(value);
          } else {
            res = await handleAdd(value);
          }

          if (res) {
            handleModalVisible(false);
            setStepFormValues({});
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }

        }}
      />
      }
      {/*<CreateForm title="添加权限" onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>*/}
      {/*  <ProTable<TableListItem, TableListItem>*/}
      {/*    onSubmit={async (value) => {*/}
      {/*      const success = await handleAdd(value);*/}
      {/*      if (success) {*/}
      {/*        handleModalVisible(false);*/}
      {/*        if (actionRef.current) {*/}
      {/*          actionRef.current.reload();*/}
      {/*        }*/}
      {/*      }*/}
      {/*    }}*/}
      {/*    rowKey="id"*/}
      {/*    type="form"*/}
      {/*    columns={columns}*/}
      {/*    rowSelection={{}}*/}
      {/*    form={{layout: 'horizontal',labelCol: { span: 6 },wrapperCol: { span: 16 }}}*/}
      {/*  />*/}
      {/*</CreateForm>*/}
      {/*{stepFormValues && Object.keys(stepFormValues).length && (*/}
      {/*  <UpdateForm*/}
      {/*    title="权限修改"*/}
      {/*    onCancel={() => {*/}
      {/*      handleUpdateModalVisible(false);*/}
      {/*      setStepFormValues(initData);*/}
      {/*    }}*/}
      {/*    updateModalVisible={updateModalVisible}*/}
      {/*  >*/}
      {/*    <ProTable<TableListItem, TableListItem>*/}
      {/*      onSubmit={async (value) => {*/}
      {/*        value.id = stepFormValues.id;*/}
      {/*        const success = await handleUpdate(value);*/}
      {/*        if (success) {*/}
      {/*          handleUpdateModalVisible(false);*/}
      {/*          setStepFormValues(initData);*/}
      {/*          if (actionRef.current) {*/}
      {/*            actionRef.current.reload();*/}
      {/*          }*/}
      {/*        }*/}
      {/*      }}*/}
      {/*      rowKey="key"*/}
      {/*      type="form"*/}
      {/*      columns={columns}*/}
      {/*      rowSelection={{}}*/}
      {/*      form={{layout: 'horizontal',labelCol: { span: 6 },wrapperCol: { span: 16 }}}*/}
      {/*    />*/}
      {/*  </UpdateForm>*/}
      {/*)}*/}

    </PageContainer>
  );

}

export default AuthConfig;
